package cn.zwx.learn.basic.mongo.listener;

import com.mongodb.client.model.changestream.ChangeStreamDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.bson.Document;
import org.springframework.data.mongodb.core.messaging.Message;
import org.springframework.data.mongodb.core.messaging.MessageListener;
import org.springframework.stereotype.Component;

/**
 * @description: 配置mongo监听器，用于接收数据库的变更信息
 * @projectName:java-basic
 * @see:cn.zwx.learn.basic.mongo.listener
 * @author:zhangwenxue
 * @createTime:2021/5/4 22:15
 * @version:1.0
 */
@Component
public class DocumentationMessageListener implements MessageListener<ChangeStreamDocument<Document>, Document> {

    private final Logger logger = LoggerFactory.getLogger(DocumentationMessageListener.class);

    /**
     * @description 感知mongoDB处理监听器
     * @return void
     * @author zhangwenxue
     * @createTime 2021/5/4 22:18
     **/
    @Override
    public void onMessage(Message<ChangeStreamDocument<Document>, Document> message) {
        message.getProperties().getCollectionName();
        logger.info("监听到mongoDB数据库:{},表:{}变化,变化类型:{},修改之后的内容:{}",
                message.getProperties().getDatabaseName(),message.getProperties().getCollectionName(),
                message.getRaw().getOperationType(),message.getBody()
                );
//        logger.info("Received Message in collection: {},message raw: {}, message body:{}",
//                message.getProperties().getCollectionName(), message.getRaw(), message.getBody());
    }
}
